package com.twu.biblioteca;

import java.util.ArrayList;
import java.util.NoSuchElementException;

public class Library {

    ArrayList<Book> books;
    ArrayList<Movie> movies;

    public Library(ArrayList<Book> bks, ArrayList<Movie> mvs) {
        books = bks;
        movies = mvs;
    }

    public ArrayList<Book> listAllBooks() { return books; }
    public ArrayList<Movie> listAllMovies() { return movies; }

    public ArrayList<Item> getAllItems() {
        ArrayList<Item> allItems = new ArrayList<Item>();
        for (Item item : movies) { allItems.add(item); }
        for (Item item : books) { allItems.add(item); }
        return allItems;
    }

    public ArrayList<Item> listAvailableBooks() {
        return getAvailableItemsOfType("book");
    }

    public ArrayList<Item> listAvailableMovies() {
        return getAvailableItemsOfType("movie");
    }

    private ArrayList<Item> getAvailableItemsOfType(String type) {
        ArrayList<Item> availableItems = new ArrayList<Item>();
        for (Item item : listAvailableItems()) {
            if (item.getType().equals(type)) {
                availableItems.add(item);
            }
        }
        return availableItems;
    }

    public ArrayList<Item> listAvailableItems() {
        ArrayList<Item> availableItems = new ArrayList<Item>();
        for (Item item : movies) {
            if (item.available) {
                availableItems.add(item);
            }
        }
        for (Item item : books) {
            if (item.available) {
                availableItems.add(item);
            }
        }
        return availableItems;
    }

    public void checkOutItem(Item item) {
        if (item.available) {
            item.available = false;
            System.out.println("Thank you! Enjoy it.");
        }
        else {
            System.out.println("That item is not available. Please choose another option:");
        }
    }

    public void returnItem(Item item) {
        if (!item.available) {
            item.available = true;
            System.out.println("Thank you for returning your item.");
        }
        else {
            System.out.println("That is not a valid item to return.");
        }
    }

    public Item getItemByTitle(String s) {
        for (Item item : this.getAllItems()) {
            if (item.getTitle().equals(s)) {
                return item;
            }
        }
        throw new NoSuchElementException("No item with title " + s + ". Please try again.");
    }

    public boolean itemExists(Book b) {
        boolean exists = false;
        for (Book book : this.listAllBooks()) {
            if (book == b) {
                exists = true;
            }
        }
        return exists;
    }

}
